<template>
  <div class="app-container">
    <div class="head-container">
      <comm-search v-if="showSearch" @search="initList()" :query-param="queryParam">
        <template #left>
          <el-form-item prop="content">
            <el-input v-model="queryParam.content" clearable placeholder="题目内容" />
          </el-form-item>
          <el-form-item prop="orders">
            <el-select style="width: 150px;" v-model="queryParam.orders" placeholder="题目顺序" filterable clearable>
              <el-option label="正序" value="0"></el-option>
              <el-option label="倒序" value="1"></el-option>
            </el-select>
          </el-form-item>
        </template>
      </comm-search>
    </div>
    <comm-tool :selections="selections" v-model:show-search="showSearch" :del-url="baseUrl" @refresh="initList()"
      @toAdd="toAddExt()" :showEdit="false" />
    <!--表单组件-->
    <comm-edit-dialog v-model:dialog-show="editDialogShow" title="题库管理" @save="toSaveExt" :save-loading="saveLoading"
      width="900px">
      <template #content>
        <el-form ref="form" :inline="true" :model="formData" :rules="rules" label-width="80px">

          <el-form-item label="顺序" prop="sequence" :min="0">
            <el-input type="number" v-model="formData.sequence" placeholder="请输入顺序" />
          </el-form-item>
          <el-form-item label="题目内容 " prop="content">
            <el-input type="textarea" :rows="5" v-model="formData.content" placeholder="请输入题目内容 " />
          </el-form-item>
          <el-form-item label="题目类型" prop="type">
            <el-radio-group v-model="formData.type" @change="changeType">
              <el-radio border :label="1">单选</el-radio>
              <el-radio border :label="2">多选</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="!showChange" label="选项列表">
            <el-button type="primary" style="margin-bottom:5px;" @click="addOption">新增选项</el-button>
            <el-table :data="options" border style="width: 100%">
              <el-table-column prop="sequence" label="顺序" width="80">
                <template #default="{ row }">
                  <el-input type="number" v-model="row.sequence" :min="0"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="label" label="选项" width="80">
                <template #default="{ row }">
                  <el-input v-model="row.label"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="content" label="内容">
                <template #default="{ row }">
                  <el-input type="textarea" :rows="2" v-model="row.content"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="answer" label="是否有子集" width="120">
                <template #default="scope">
                  <el-switch style="display: block" v-model="scope.row.answer" :active-value="1" :inactive-value="0"
                    @change="changeAnswer(scope)">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" fixed="right">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="deleteOption(scope)">删除</el-button>
                  <!-- 添加子类型 -->
                  <el-button v-if="scope.row.answer == 1" type="primary" size="small" @click="openSubsetDialog(scope, scope.$index)">子集</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </template>
    </comm-edit-dialog>
    <!--表格渲染-->
    <el-tabs @tab-change="changeTab" v-model="activeName">
      <el-tab-pane label="单选题" name="1"></el-tab-pane>
      <el-tab-pane label="多选题" name="2"></el-tab-pane>
    </el-tabs>
    <el-table :loading="loading" :data="dataList" @selectionChange="selectionChange">
      <el-table-column type="selection" />
      <el-table-column prop="sequence" label="顺序" width="50" />
      <el-table-column prop="content" label="内容" />
      <el-table-column prop="type" label="类型" width="80">
        <template #default="scope">
          <!-- <span v-if="scope.row.type===0">判断</span> -->
          <span v-if="scope.row.type===1">单选</span>
          <span v-if="scope.row.type===2">多选</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" align="center" fixed="right" width="120">
        <template #default="scope">
          <comm-operation :data="scope.row" :url="baseUrl" @edit="toEditExt(scope.row)" @refresh="initList()" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:page="queryParam.page" v-model:limit="queryParam.size" :total="total" @change="initList()" />
    <comm-edit-dialog v-model:dialog-show="subsetDialogShow" title="子集管理" @save="toSaveSubset" :save-loading="saveLoading"
      width="900px">
      <template #content>
        <el-form ref="subsetForm" :inline="true" :model="subsetFormData" :rules="subsetRules" label-width="80px">
          <el-form-item label="题目内容 " prop="content">
            <el-input type="textarea" :rows="5" v-model="subsetFormData.content" placeholder="请输入题目内容 " />
          </el-form-item>
          <el-form-item label="题目类型" prop="type">
            <el-radio-group v-model="subsetFormData.type">
              <el-radio border :label="1">单选</el-radio>
              <el-radio border :label="2">多选</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选项列表">
            <el-button type="primary" style="margin-bottom:5px;" @click="addSubsetOption">新增选项</el-button>
            <el-table :data="subsetOptions" border style="width: 100%">
              <el-table-column label="顺序" prop="sequence" :min="0">
                <template #default="{ row }">
                  <el-input type="number" v-model="row.sequence" placeholder="请输入顺序" />
                </template>
              </el-table-column>

              <el-table-column prop="label" label="选项" width="80">
                <template #default="{ row }">
                  <el-input v-model="row.label"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="content" label="内容">
                <template #default="{ row }">
                  <el-input type="textarea" :rows="2" v-model="row.content"></el-input>
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center" fixed="right">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="deleteSubsetOption(scope)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </template>
    </comm-edit-dialog>
  </div>
</template>


<script setup>
  import { getCurrentInstance, reactive, ref, toRefs } from 'vue'
  import Pagination from '@/components/Pagination'
  import mixins from "@/mixins/mixins";
  import CommSearch from "@/components/Comm/CommSearch.vue";
  import CommTool from "@/components/Comm/CommTool.vue";
  import CommEditDialog from "@/components/Comm/CommEditDialog.vue";
  import CommOperation from "@/components/Comm/CommOperation.vue";
  import { get, post } from "@/utils/request";
  import { ElMessage } from 'element-plus';

  const pageData = reactive({
    rules: {
      sequence: [
        { required: true, message: '顺序不能为空', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '题目内容 不能为空', trigger: 'blur' }
      ],
    }
  })

  const { initList, total, dataList, data, selectionChange, toAdd, toEdit, toSave } = mixins()
  const { queryParam, loading, saveLoading, selections, showSearch, editDialogShow, baseUrl, formData } = toRefs(data)

  const { rules } = toRefs(pageData)

  const { proxy } = getCurrentInstance();

  const options = ref([])

  const activeName = ref("1")
  queryParam.value.type = '1'
  baseUrl.value = '/question'
  initList()

  const addOption = () => {
    options.value.push({
      'sequence': 0,
      'label': '',
      'content': '',
      'answer': 0,
    })
  }
  const showChange = ref(true)
  const deleteOption = (row) => {
    options.value.splice(row.$index, 1);
  }
  const toAddExt = () => {
    let value = {
      'id': 0,
      'sequence': '',
      'content': '',
      'type': 0,
      'remark': '',
      'answer': 0
    }
    options.value = []
    showChange.value = true
    toAdd(value, 'form')
  }
  const toEditExt = (row) => {
    get('/question/options', { id: row.id }).then(res => {
      if (res) {
        options.value = res
        showChange.value = 0 === row.type
        toEdit(row, 'form')
      }
    })
  }
  const toSaveExt = () => {
    post('/question/save', {
      detail: formData.value,
      options: options.value
    }).then(res => {
      if (res) {
        ElMessage({
          message: '编辑成功',
          type: 'success'
        });
        editDialogShow.value = false
        activeName.value = formData.value.type + ""
        queryParam.value.type = formData.value.type + ''
        initList()
      }
    })
  }
  const changeType = (value) => {
    showChange.value = 0 === value
    if (1 === value) {
      for (let i = 0; i < options.value.length; i++) {
        options.value[i].answer = 0
      }
    }
  }
  const changeAnswer = (scope) => {
    // if (1 === formData.value.type && 1 === scope.row.answer) {
    //   for (let i = 0; i < options.value.length; i++) {
    //     if (scope.$index !== i) {
    //       options.value[i].answer = 0
    //     }
    //   }
    // }
  }
  const changeTab = (value) => {
    queryParam.value.type = value + ''
    queryParam.value.page = 1
    initList()
  }
  const subsetDialogShow = ref(false)
  const subsetFormData = ref({})
  const subsetRules = {
    content: [
      { required: true, message: '题目内容 不能为空', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '题目类型不能为空', trigger: 'blur' }
    ]
  }
  const subsetOptions = ref([])

  const addSubsetOption = () => {
    subsetOptions.value.push({
      'label': '',
      'content': '',
      'sequence': 0,
    })
  }
  const deleteSubsetOption = (row) => {
    subsetOptions.value.splice(row.$index, 1);
  }
  const toSaveSubset = () => {
   let tempoptions = subsetOptions.value.map(option => ({
      label: option.label,
      content: option.content,
      sequence: option.sequence,
    }));
    let tempdetail = subsetFormData.value
    
    options.value[optionsIndex.value].questionExtDto = {
      detail: tempdetail,
      options: tempoptions
    }

    subsetDialogShow.value = false;
    // post('/question/save', {
    //   detail: formData.value,
    //   options: options.value
    // }).then(res => {
    //   console.log('返回结果', res)
    // })
     
  }
  let optionsIndex = ref(null)
  const openSubsetDialog = (scope, index) => {
    console.log('下标', scope)
    optionsIndex.value = index
    const {questionExtDto} = scope.row
    if (questionExtDto) {
      subsetFormData.value = questionExtDto.detail
      subsetOptions.value = questionExtDto.options
    } else {
      subsetFormData.value = {
        content: '',
        type: '',
        sequence: 0
      }
      subsetOptions.value = [];
    }
    
    console.log('Subset options:', subsetOptions.value);
    subsetDialogShow.value = true;
    console.log('Subset dialog show:', subsetDialogShow.value);
  }
</script>